package com.code.day21;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

public class DemoFileServerClient {
    public static void main(String[] args) throws Exception {
        //1.创建ServerSocket对象
        ServerSocket serverSocket = new ServerSocket(6666);
        //2.调用accept方法,获取到客户端的Socket对象
        Socket socket = serverSocket.accept();
        String name = UUID.randomUUID().toString();
        
        //3.创建FileOutputStream,用于将读取过来的图片写到本地上  此时还没有读 而是指定往哪里写
        FileOutputStream fos = new FileOutputStream("D:\\java-code\\java-full-stack\\01-java-base\\src\\com\\code\\day21\\file\\"+name+".jpg");
        //4.调用Socket中的getInputStream,用于读取客户端发送过来的图片
        InputStream inputStream = socket.getInputStream();
        //5.边读边写
        byte[] bytes = new byte[1024];
        int len=0;
        while((len=inputStream.read(bytes))!=-1){
            fos.write(bytes,0,len);
        }
        System.out.println("==========以下代码是响应代码=========");
        //6.获取getOutputStream,用于给客户端响应数据
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("上传成功".getBytes());
        //7.关闭资源
        fos.close();
        inputStream.close();
        outputStream.close();
        socket.close();
        serverSocket.close();
    }
}
